package com.gitee.wsl.jvm.okhttp.intercept.updown

import android.content.Context
import android.net.Uri
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


/**
 * User: ljx
 * Date: 2022/9/27
 * Time: 17:16
 */
class ExpandOutputStream<T>(val expand: T, private val os: OutputStream?) : OutputStream() {

    @Throws(IOException::class)
    override fun write(b: Int) {
        os!!.write(b)
    }

    @Throws(IOException::class)
    override fun write(b: ByteArray) {
        os!!.write(b)
    }

    @Throws(IOException::class)
    override fun write(b: ByteArray, off: Int, len: Int) {
        os!!.write(b, off, len)
    }

    @Throws(IOException::class)
    override fun close() {
        os!!.close()
    }

    @Throws(IOException::class)
    override fun flush() {
        os!!.flush()
    }

    companion object {
        @Throws(FileNotFoundException::class)
        fun open(file: File, append: Boolean): ExpandOutputStream<String> {
            return ExpandOutputStream(file.absolutePath, FileOutputStream(file, append))
        }

        @Throws(FileNotFoundException::class)
        fun open(context: Context, uri: Uri, append: Boolean): ExpandOutputStream<Uri> {
            val os = context.contentResolver.openOutputStream(uri, if (append) "wa" else "w")
            return ExpandOutputStream(uri, os)
        }
    }
}